package com.xjrsoft.module.organization.service.impl;


import cn.dev33.satoken.secure.SaSecureUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.utils.WeChatUtil;
import com.xjrsoft.config.CommonPropertiesConfig;
import com.xjrsoft.module.organization.dto.WeChatDepartDto;
import com.xjrsoft.module.organization.dto.WeChatUserDto;
import com.xjrsoft.module.organization.entity.Department;
import com.xjrsoft.module.organization.entity.User;
import com.xjrsoft.module.organization.entity.UserDeptRelation;
import com.xjrsoft.module.organization.service.IDepartmentService;
import com.xjrsoft.module.organization.service.IUserDeptRelationService;
import com.xjrsoft.module.organization.service.IUserService;
import com.xjrsoft.module.organization.service.WeChatService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class WeChatServiceImgl implements WeChatService {

    private final IDepartmentService departmentService;

    private final IUserService userService;

    private final IUserDeptRelationService userDeptRelationService;

    private final WeChatUtil weChatUtil;

    private final CommonPropertiesConfig propertiesConfig;

    @Override
    public boolean syncDepartments(Long departmentId) {
        Long weChatDeptId = null;
        if (ObjectUtils.isNotEmpty(departmentId)) {
            Department pDepartment = departmentService.getById(departmentId);
            if (pDepartment.getWechatDeptId() == null) throw new RuntimeException("部门“" + pDepartment.getName() + "”尚未同步！");
            weChatDeptId = pDepartment.getWechatDeptId();
        }
        List<WeChatDepartDto> weChatDeptList = weChatUtil.getWeChatDepartmentList(weChatDeptId);
        if (CollectionUtils.isNotEmpty(weChatDeptList)) {
            List<Long> weChatDeptIdList = weChatDeptList.stream().map(WeChatDepartDto::getId).collect(Collectors.toList());
            List<Department> departmentList = departmentService.list(Wrappers.lambdaQuery(Department.class)
                    .select(Department::getId, Department::getWechatDeptId)
                    .in(Department::getWechatDeptId, weChatDeptIdList));
            // id映射，key：企业微信部门id，value：系统部门id
            Map<Long, Long> idMap = new HashMap<>(weChatDeptIdList.size());
            List<Department> updateDepartmentList = new ArrayList<>(weChatDeptList.size());
            for (WeChatDepartDto weChatDepartDto : weChatDeptList) {
                boolean exist = false;
                Long id = null;
                Department updateDepartment = new Department();
                for (Department department : departmentList) {
                    if (weChatDepartDto.getId().equals(department.getWechatDeptId())) {
                        id = department.getId();
                        exist = true;
                        break;
                    }
                }
                if (!exist) {
                    id = IdUtil.getSnowflakeNextId();
                }
                updateDepartment.setName(weChatDepartDto.getName());
                updateDepartment.setCode(weChatDepartDto.getName_en());
                updateDepartment.setId(id);
                updateDepartment.setWechatDeptId(weChatDepartDto.getId());
                updateDepartment.setParentId(weChatDepartDto.getParentid());
                updateDepartmentList.add(updateDepartment);
                idMap.put(weChatDepartDto.getId(), id);
            }
            // 处理上级部门
            for (Department updateDepartment : updateDepartmentList) {
                Long parentId = idMap.get(updateDepartment.getParentId());
                updateDepartment.setParentId(parentId == null ? 0L : parentId);
            }
            return departmentService.saveOrUpdateBatch(updateDepartmentList);
        }
        return true;
    }

    @Override
    @Transactional
    public boolean syncUsers(Long departmentId) {
        Department department = departmentService.getById(departmentId);
        if (department.getWechatDeptId() == null) {
            throw new RuntimeException("请先同步部门！");
        }
        List<WeChatUserDto> weChatUserList = weChatUtil.getWeChatUsersOfDepartment(department.getWechatDeptId());
        if (CollectionUtils.isNotEmpty(weChatUserList)) {
            List<String> weChatUserIds = weChatUserList.stream().map(WeChatUserDto::getUserid).collect(Collectors.toList());
            List<User> userList = userService.list(Wrappers.lambdaQuery(User.class).in(User::getWechatUserId, weChatUserIds));
            List<User> updateUserList = new ArrayList<>(weChatUserList.size());
            List<UserDeptRelation> userDeptRelationList = new ArrayList<>(weChatUserList.size());
            List<Long> updateUserIdList = new ArrayList<>(weChatUserList.size());
            for (WeChatUserDto weChatUserDto : weChatUserList) {
                User updateUser = new User();
                Long userId = null;
                boolean exist = false;
                for (User user : userList) {
                    if (StrUtil.equals(weChatUserDto.getUserid(), user.getWechatUserId())) {
                        userId = user.getId();
                        exist = true;
                        break;
                    }
                }
                if (!exist) {
                    userId = IdUtil.getSnowflakeNextId();
                    // 默认密码
                    updateUser.setPassword(SaSecureUtil.md5BySalt(propertiesConfig.getDefaultPassword(), GlobalConstant.SECRET_KEY));
                }
                // 构建同步的user信息
                updateUser.setId(userId);
                updateUser.setUserName(weChatUserDto.getUserid());
                updateUser.setName(weChatUserDto.getName());
                updateUser.setMobile(weChatUserDto.getMobile());
                updateUser.setEmail(weChatUserDto.getEmail());
                String gender = weChatUserDto.getGender();
                if (StrUtil.isNotEmpty(gender)) {
                    if (StrUtil.equalsIgnoreCase(gender, "1")) {
                        updateUser.setGender(1);
                    } else if (StrUtil.equalsIgnoreCase(gender, "2")) {
                        updateUser.setGender(0);
                    }
                }
                updateUser.setWechatUserId(weChatUserDto.getUserid());
                updateUserList.add(updateUser);
                // 构建用户部门关系
                UserDeptRelation userDeptRelation = new UserDeptRelation();
                userDeptRelation.setUserId(userId);
                userDeptRelation.setDeptId(departmentId);
                userDeptRelationList.add(userDeptRelation);

                updateUserIdList.add(userId);
            }
            userService.saveOrUpdateBatch(updateUserList);
            // 删除旧的部门用户关联关系
            userDeptRelationService.remove(Wrappers.lambdaQuery(UserDeptRelation.class)
                    .eq(UserDeptRelation::getDeptId, departmentId)
                    .in(UserDeptRelation::getUserId, updateUserIdList));
            userDeptRelationService.saveBatch(userDeptRelationList);
            return true;
        } else {
            throw new RuntimeException("企业微信没有人员！");
        }
    }

}
